﻿/* 4. Write a program, that reads from the console an array of N integers and an integer K, 
 * sorts the array and using the method Array.BinSearch() finds the largest number in the array which is ≤ K. */

using System;

public class SortingAndBinSearch
{
    public static int n;
    public static int[] array;
    public static int k;

    public static void Main()
    {
        DataInput();
        Array.Sort(array);
        CheckAndPrintResult();
    }

    public static void DataInput()
    {
        do
        {
            Console.Clear();
            Console.Write("\nN = ");
            if ((int.TryParse(Console.ReadLine(), out n)) && (0 < n))
            {
                array = new int[n];

                for (int i = 0; i < n; i++)
                {
                    do
                    {
                        Console.Clear();
                        Console.Write("\nN = {0}\n\n", n);
                        for (int j = 0; j < i; j++)
                            Console.WriteLine("array[{0}] = {1}", j, array[j]);

                        Console.Write("array[{0}] = ", i);
                        if (int.TryParse(Console.ReadLine(), out array[i]))
                            break;
                    } while (true);
                }

                do
                {
                    Console.Clear();
                    Console.Write("\nN = {0}\n\n", n);
                    for (int i = 0; i < n; i++)
                        Console.WriteLine("array[{0}] = {1}", i, array[i]);

                    Console.Write("\nK = ");
                    if (int.TryParse(Console.ReadLine(), out k))
                        break;
                } while (true);

                break;
            }
        } while (true);

        Console.WriteLine();
    }

    public static void CheckAndPrintResult()
    {
        int result = Array.BinarySearch(array, k);

        if (result < 0)
        {
            result = -result;
            if (n < result)
                result = n - 1;
            else
                result -= 2;
        }

        if (0 <= result)
            Console.WriteLine("The largest number in the array which is not larger than K is {0}\n", array[result]);
        else
            Console.WriteLine("There is no such member!\n");
    }
}